// pages/received-flowers/received-flowers.js
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const app = getApp();

Page({
  data: {
    // 统计数据
    totalReceived: 0,
    todayReceived: 0,
    matchedCount: 0,
    
    // 记录列表
    recordList: [],
    
    // 分页信息
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    loading: false
  },

  onLoad(options) {
    console.log('收到的花页面加载');
    this.loadData();
  },

  onShow() {
    console.log('收到的花页面显示');
  },

  onPullDownRefresh() {
    console.log('下拉刷新');
    this.refreshData();
  },

  onReachBottom() {
    console.log('上拉加载更多');
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreData();
    }
  },

  // 加载数据
  async loadData() {
    try {
      await Promise.all([
        this.loadStatistics(),
        this.loadRecordList()
      ]);
    } catch (error) {
      console.error('加载数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    }
  },

  // 加载统计数据
  async loadStatistics() {
    try {
      // 从API加载统计数据
      const response = await api.getReceivedFlowerStats();
      
      const stats = response && response.code === 0 ? response.data : {
        totalReceived: 0,
        todayReceived: 0,
        matchedCount: 0
      };
      
      this.setData(stats);
      
    } catch (error) {
      console.error('加载统计数据失败:', error);
      throw error;
    }
  },

  // 加载记录列表
  async loadRecordList() {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    try {
      const { pageNum, pageSize } = this.data;
      
      // 从API加载收花记录
      const response = await api.getReceivedFlowerRecords({
        pageNum: pageNum,
        pageSize: pageSize
      });
      
      if (response && response.code === 0 && response.data) {
        const records = response.data.recordList || [];
        
        if (pageNum === 1) {
          this.setData({ recordList: records });
        } else {
          this.setData({ 
            recordList: [...this.data.recordList, ...records] 
          });
        }

        this.setData({
          hasMore: records.length === pageSize,
          pageNum: pageNum + 1
        });
      }

    } catch (error) {
      console.error('加载记录列表失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
      wx.stopPullDownRefresh();
    }
  },


  // 刷新数据
  refreshData() {
    this.setData({ 
      pageNum: 1,
      recordList: [],
      hasMore: true
    });
    this.loadData();
  },

  // 加载更多数据
  loadMoreData() {
    this.loadRecordList();
  },

  // 记录项点击
  onRecordTap(e) {
    const user = e.currentTarget.dataset.user;
    wx.navigateTo({
      url: `/pages/profile/profile?userNum=${user.userNum}`
    });
  },

  // 回花
  async onSendFlowerBack(e) {
    e.stopPropagation();
    const user = e.currentTarget.dataset.user;
    const currentUser = app.globalData.currentUser;
    
    // 检查登录状态
    if (!currentUser.isLogin) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    try {
      wx.showLoading({ title: '回花中...' });
      
      // 调用送花API
      await api.sendFlower(currentUser.userNum, user.userNum);
      
      // 更新记录状态
      const recordList = this.data.recordList.map(record => {
        if (record.id === user.id) {
          return { ...record, status: 'matched' };
        }
        return record;
      });
      
      this.setData({ recordList });
      
      // 更新本地送花状态
      const todayFlowerKey = `todayFlower_${util.formatDate(new Date())}`;
      const todayFlowerSent = wx.getStorageSync(todayFlowerKey) || {};
      todayFlowerSent[user.userNum] = true;
      wx.setStorageSync(todayFlowerKey, todayFlowerSent);
      
      wx.showToast({
        title: '回花成功！匹配啦~',
        icon: 'success'
      });
      
      // 显示匹配成功提示
      setTimeout(() => {
        wx.showModal({
          title: '匹配成功！',
          content: `恭喜您与${user.name}匹配成功！请联系管理员进行线下牵线。`,
          confirmText: '联系管理员',
          cancelText: '稍后联系',
          success: (res) => {
            if (res.confirm) {
              this.contactAdmin();
            }
          }
        });
      }, 1500);
      
    } catch (error) {
      console.error('回花失败:', error);
      wx.showToast({
        title: '回花失败',
        icon: 'error'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 联系用户
  onContactUser(e) {
    e.stopPropagation();
    const user = e.currentTarget.dataset.user;
    
    wx.showModal({
      title: '联系TA',
      content: `您与${user.name}匹配成功！请联系管理员进行线下牵线。\n\n管理员微信：yuanlaixiangyu_admin`,
      confirmText: '复制微信号',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          this.contactAdmin();
        }
      }
    });
  },

  // 查看资料
  onViewProfile(e) {
    e.stopPropagation();
    const user = e.currentTarget.dataset.user;
    wx.navigateTo({
      url: `/pages/profile/profile?userNum=${user.userNum}`
    });
  },

  // 联系管理员
  contactAdmin() {
    wx.setClipboardData({
      data: 'yuanlaixiangyu_admin',
      success: () => {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        });
      }
    });
  },

  // 去完善资料
  onGoToEdit() {
    wx.navigateTo({
      url: '/pages/edit-profile/edit-profile'
    });
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'pending': '待回应',
      'matched': '匹配',
      'responded': '已回应',
      'expired': '过期'
    };
    return statusMap[status] || '未知';
  },

  // 获取操作文本
  getActionText(status) {
    const actionMap = {
      'pending': '等待回花',
      'matched': '匹配成功',
      'responded': '已回应',
      'expired': '已过期'
    };
    return actionMap[status] || '未知状态';
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '我收到的花 - 青鸟传信',
      path: '/pages/index/index',
      imageUrl: '/assets/images/share-image.png'
    };
  }
});